package com.jsg.sl651.entity.frame.header;

import com.jsg.sl651.enums.CommunicationMessageType;
import com.jsg.sl651.util.ByteUtil;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * M3模式时分包信息
 */
@Data
@Accessors(chain = true)
public class PacketInfo implements Serializable {
    // 总包数
    private int totalNumber;
    // 包序号
    private int packetNumber;

    public PacketInfo(byte[] bytes) {
        if (bytes.length != 3) {
            throw new RuntimeException("数据长度不对,数据长度必须为 3 ,当前长度： " + bytes.length);
        }
        // 整合成一个
        this.totalNumber = (bytes[0] & 0XFF) << 4 | (bytes[1] & 0XFF) >> 4;
        this.packetNumber = (bytes[1] & 0X0F) << 8 | bytes[2] & 0XFF;
    }

    public byte[] toBodyBytes(CommunicationMessageType type) {
        byte[] bytes = new byte[3];
        // 将 totalNumber 的高8位放入 bytes[0]
        bytes[0] = (byte) ((totalNumber >> 4) & 0XFF);
        // 将 totalNumber 的低4位放入 bytes[1] 的高4位，将 packetNumber 的高4位放入 bytes[1] 的低4位
        bytes[1] = (byte) (((totalNumber & 0X0F) << 4) | ((packetNumber >> 8) & 0X0F));
        // 将 packetNumber 的低8位放入 bytes[2]
        bytes[2] = (byte) (packetNumber & 0XFF);
        if (type == CommunicationMessageType.HEX) {
            return bytes;
        } else {
            return ByteUtil.stringToSimpleByteArray(ByteUtil.toHex(bytes));
        }
    }
}
